'use strict';

const Controller = require('egg').Controller;
const md5 = require('md5')

class CreateaccountController extends Controller {
  async createAccount() {
    const { ctx } = this
    const { username, password, contact } = ctx.request.body
    const md5Password = md5(password)
    const isExistUsername = await ctx.service.user.findByUsername(username)
    // 用户名不存在, 可以添加新用户
    if (isExistUsername === null) {
      const result = await ctx.service.user.createUser(username, md5Password, contact)
      if (result.affectedRows === 1) {
        ctx.body = {
          code: 1,
          msg: '账户添加成功'
        }
        return
      }
    }
    // 用户名已存在
    ctx.body = {
      code: 0,
      msg: '用户名已存在'
    }
  }
}

module.exports = CreateaccountController;
